package ewgenius.testgame.main.objects;

import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.util.vector.Vector3f;

import ewgenius.xube.XubeEngine;
import ewgenius.xube.engine.InputState;
import ewgenius.xube.engine.entities.Entity;
import ewgenius.xube.engine.graphics.Render;
import static ewgenius.xube.engine.physics.PhysicsEngine.*;

public class Player extends Entity {

	private float speed = 20;

	public Player() {
		super("player", 0);
		Mouse.setGrabbed(true);
	}

	@Override
	public void update(int time, XubeEngine engine) {

		InputState input = engine.getInputState();
		// rotation = new Vector3f(20, 0, 0);

		float cos = (float) Math.cos(rotation.y / 180 * Math.PI);
		float sin = (float) Math.sin(rotation.y / 180 * Math.PI);
		Vector3f direction = new Vector3f(-sin, 0, cos);

		// forward
		if (input.keyUp) {
			position.x += speed * time * second * direction.x;
			position.z += speed * time * second * direction.z;
		}
		// backward
		if (input.keyDown) {
			position.x -= speed * time * second * direction.x;
			position.z -= speed * time * second * direction.z;
		}

		// up
		if (input.keyShift) {
			position.y -= speed * time * second;
		}
		// down
		if (input.keyCtrl) {
			position.y += speed * time * second;
		}

		// left
		if (input.keyLeft) {
			position.x += speed * time * second * direction.z;
			position.z -= speed * time * second * direction.x;
		}
		// right
		if (input.keyRight) {
			position.x -= speed * time * second * direction.z;
			position.z += speed * time * second * direction.x;
		}

		// Mouse.setGrabbed(true);

		Display.setTitle(rotation.x + " " + rotation.y + " " + rotation.z
				+ " | " + direction.x + " " + direction.y + " " + direction.z);

		if (Mouse.isGrabbed()) {
			float mouseDX = input.mouseDX * time * 0.0006f;
			float mouseDY = input.mouseDY * time * 0.0006f;

			rotation.y += mouseDX;

			if (rotation.y >= 360) {
				rotation.y -= 360;
			} else if (rotation.y < 0) {
				rotation.y += 360;
			}
			if (rotation.x - mouseDY >= -85 && rotation.x - mouseDY <= 85) {
				rotation.x += -mouseDY;
			} else if (rotation.x - mouseDY < -85) {
				rotation.x = -85;
			} else if (rotation.x - mouseDY > 85) {
				rotation.x = 85;
			}
		}
	}

	@Override
	public void render(Render render) {
		// TODO Auto-generated method stub
		render.updateCamera(position, rotation);
	}
}
